package com.manager.web.system;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.manager.base.BaseAction;
import com.manager.pojo.system.SysRole;
import com.manager.util.DateUtil;
import com.manager.util.Log;
import com.opensymphony.xwork2.Action;

public class SysRoleAction extends BaseAction {
	private SysRole sysRole;
	
	/*
	 * 添加角色
	 */
	public String addRole(){
		String privileges = request.getParameter("privileges");
		int loginUserId = super.getLoginUserId();
		PrintWriter p = null;
		
		try{
			p = response.getWriter();
			
			//查询角包名是否已存在
			int total = super.baseService.queryInt("select count(1) from sys_role where name = ?", sysRole.getName());
			if(total == 1){
				p.print("{\"flag\":false,\"msg\":\"该角色已存在\"}");
			}else{
				//添加角色
				SysRole sr = new SysRole();
				sr.setName(sysRole.getName());
				sr.setUpdateById(loginUserId);
				sr.setUpdateDateTime(DateUtil.getCurrentDateTime(true));
				sr.setCreateById(loginUserId);
				sr.setCreateDateTime(DateUtil.getCurrentDateTime(true));
				super.baseService.save(sr);
				
				//添加角色对应的权限
				if(privileges != null &&  !privileges.equals("")){
					String[] ct = request.getParameter("privileges").toString().split(",");
					String sql = "INSERT INTO sys_role_privilege (role_id, privilege_id, create_by_id, create_date_time, update_by_id, update_date_time) VALUES (?,?,?,?,?,?)";
					
					Object[][] params = new Object[ct.length][6];
					for(int i = 0; i < ct.length; i++){
						params[i][0] = sr.getId();
						params[i][1] = Integer.parseInt(ct[i]);
						params[i][2] = loginUserId;
						params[i][3] = DateUtil.getCurrentDateTime(true);
						params[i][4] = loginUserId;
						params[i][5] = DateUtil.getCurrentDateTime(true);
					}
					super.baseService.executeBatch(sql, params);
				}
				
				p.print("{\"flag\":true}");
			}
		}catch(Exception e){
			p.print("{\"flag\":false}");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		
		return Action.NONE;
	}
	
	/*
	 * 删除角色
	 */
	public String deleteRole(){
		int roleId = sysRole.getId();
		PrintWriter p = null;
		
		try{
			p = response.getWriter();
			
			//永远不允许删除"临时角色"
			if(roleId == 2){
				p.write("{\"flag\":false,\"msg\":\"永远不允许删除--临时角色\"}");
			}else{
				//删除该角色
				super.baseService.delete("delete from sys_role where id = ?", roleId);
				//删除该角色其下的所有权限
				super.baseService.delete("delete from sys_role_privilege where role_id = ?", roleId);
				//将该角色其下的所有人员的role_id置为2(临时角色)
				super.baseService.update("update sys_user_role set role_id = 2 where role_id = ?", roleId);
				
				p.print("{\"flag\":true}");
			}
		}catch(Exception e){
			p.print("{\"flag\":false}");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		return Action.NONE;
	}
	
	/*
	 * 更新role
	 */
	public String updateRole(){
		String privileges = request.getParameter("privileges");
		int loginUserId = super.getLoginUserId();
		PrintWriter p = null;
		
		try{
			p = response.getWriter();
			
			//查询除该id角色外，其它所有角包中该角色名是否存在
			int total = super.baseService.queryInt("select count(1) from sys_role where name = ? and id != ?", sysRole.getName(), sysRole.getId());
			if(total == 1){
				p.print("{\"flag\":false,\"msg\":\"该角色已存在\"}");
			}else{
				//更新role数据
				LinkedHashMap<String, Object> setParams = new LinkedHashMap<String, Object>();
				setParams.put("name", sysRole.getName());
				setParams.put("update_by_id", super.getLoginUserId());
				setParams.put("update_date_time", DateUtil.getCurrentDateTime(true));
				
				LinkedHashMap<String, Object> whereParams = new LinkedHashMap<String, Object>();
				whereParams.put("id", sysRole.getId());
				
				super.baseService.update("sys_role", setParams, whereParams);
				
				//删除老权限
				super.baseService.delete("delete from sys_role_privilege where role_id = ?", sysRole.getId());
				
				//添加新权限
				if(privileges != null &&  !privileges.equals("")){
					String[] ct = privileges.split(",");
					String sql = "INSERT INTO sys_role_privilege (role_id, privilege_id, create_by_id, create_date_time, update_by_id, update_date_time) VALUES (?,?,?,?,?,?)";
					
					Object[][] params = new Object[ct.length][6];
					for(int i = 0; i < ct.length; i++){
						params[i][0] = sysRole.getId();
						params[i][1] = Integer.parseInt(ct[i]);
						params[i][2] = loginUserId;
						params[i][3] = DateUtil.getCurrentDateTime(true);
						params[i][4] = loginUserId;
						params[i][5] = DateUtil.getCurrentDateTime(true);
					}
					super.baseService.executeBatch(sql, params);
				}
				
				p.print("{\"flag\":true}");
			}
		}catch(Exception e){
			p.print("{\"flag\":false}");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		
		return Action.NONE;
	}
	
	/*
	 * 由ID查询role所拥有的所有privilege
	 */
	public String queryRoleById(){
		int roleId = sysRole.getId();
		
		sysRole = super.baseService.getObject(SysRole.class, roleId);
		
		String rs = super.baseService.queryString("select cast(group_concat(privilege_id) as char) privileges from sys_role_privilege where role_id = ?", roleId);
		
		request.setAttribute("privileges", rs);
		super.forward("system/roleUpdate.jsp");
		return Action.NONE;
	}
	
	/*
	 * 查询权限及所属菜单，以供jquery filetree使用
	 */
	public String queryMenuPrivilege() {
		String root = request.getParameter("jqueryFiletreeId");
		PrintWriter p = null;
		int id = -1;
		StringBuffer sb = new StringBuffer();
		
		try{
			p = response.getWriter();
			
			if(root == null || root.equals("null")){
				p.flush();
				p.close();
				return Action.NONE;
			}else if(root.equals("source")){
				id = -1;
			}else{
				id = Integer.parseInt(root);
			}
			
			List list = this.baseService.callProList("PRO_QUERY_MENU_PRIVILEGE", id);
			
			if(list.size() > 0){
				sb.delete(0, sb.length());
				
				sb.append("<ul class=\"jqueryFileTree\" style=\"display: none;\">");
				for(int i = 0; i < list.size(); i++){
					Map m = (Map)list.get(i);
					
					if(m.get("leaf").toString().equals("0")){
						sb.append("<li class=\"directory collapsed\">");
							sb.append("<input type=\"checkbox\" style=\"display:none;\" value=\"" + m.get("id").toString() + "\"/>");
							sb.append("<a href=\"#\" rel=\"" + m.get("id").toString() + "\">" + m.get("name").toString() + "</a>");
						sb.append("</li>");
					}else{
						sb.append("<li class=\"file ext_code leaf\">");
							sb.append("<input type=\"checkbox\" style=\"display:none;\" value=\"" + m.get("id").toString() + "\"/>");
							sb.append("<a href=\"#\" target=\"mainRight\">" + m.get("name").toString() + "</a>");
						sb.append("</li>");
					}
					
				}
				sb.append("</ul>");
				
				p.print(sb.toString());
			}else{
				
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		
		return Action.NONE;
	}
	
	/*
	 * 查询所有的role，提供给jquery filetree使用
	 */
	public String queryRoleAll(){
		String root = request.getParameter("jqueryFiletreeId");
		PrintWriter p = null;
		StringBuffer sb = new StringBuffer();
		String sql = null;
		
		try{
			p = response.getWriter();
			
			if(root.equals("source")){
				sql = "select id, name from sys_role order by id desc";
			}else{
				p.flush();
				p.close();
				return Action.NONE;
			}
			
			List list = this.baseService.queryList(sql);
			
			if(list.size() > 0){
				sb.append("<ul class=\"jqueryFileTree\" style=\"display: none;\">");
				for(int i = 0; i < list.size(); i++){
					Map m = (Map)list.get(i);
					
					sb.append("<li class=\"directory collapsed\">");
						sb.append("<input type=\"checkbox\" style=\"display:none;\" value=\"" + m.get("id").toString() + "\"/>");
						sb.append("<a href=\"#\" rel=\"" + m.get("id").toString() + "\">" + m.get("name").toString() + "</a>");
					sb.append("</li>");
					
				}
				sb.append("</ul>");
				Log.info("menuAll:" + sb.toString());
				p.print(sb.toString());
			}else{
				p.print("there is no role!!");
			}
			
		}catch(Exception e){
			p.print("error!!");
			e.printStackTrace();
		}finally{
			p.flush();
			p.close();
		}
		
		return Action.NONE;
	}
	
	/*
	 * getter and setter
	 */
	public SysRole getSysRole() {
		return sysRole;
	}

	public void setSysRole(SysRole sysRole) {
		this.sysRole = sysRole;
	}
}
